const express = require('express');
const router = express.Router();
const URLProcessor = require('../src/utils/urlProcessor');
const VideoDownloader = require('../src/services/videoDownloader');
const TextExtractor = require('../src/services/textExtractor');

router.post('/extract', async (req, res) => {
    try {
        console.log('收到提取请求:', req.body);
        const { url } = req.body;
        
        if (!url) {
            return res.status(400).json({ error: '请提供视频链接' });
        }

        const videoId = await URLProcessor.extractDouyinVideoId(url);
        if (!videoId) {
            return res.status(400).json({ error: '无法解析视频链接' });
        }

        const downloader = new VideoDownloader();
        const videoPath = await downloader.downloadVideo(videoId);
        if (!videoPath) {
            return res.status(500).json({ error: '视频下载失败' });
        }

        const extractor = new TextExtractor();
        const text = await extractor.extractText(videoPath);

        res.json({ text: text || '未能识别到文字内容' });
    } catch (error) {
        console.error('处理请求失败:', error);
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;